package com.thn.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.thn.user.model.LoginRequest;
import com.thn.user.model.RegisterRequest;
import com.thn.user.model.User;
import com.thn.user.service.UserService;
import com.thn.user.mapper.UserMapper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
* @author jzg
* @description 针对表【user】的数据库操作Service实现
* @createDate 2025-07-14 14:13:01
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public User login(LoginRequest loginRequest) {
        String username = loginRequest.getUsername();
        String rawPassword = loginRequest.getPassword();

        // 查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = getOne(queryWrapper);

        if (user == null) {
            throw new RuntimeException("用户名不存在");
        }

        // 验证密码
        if (!passwordEncoder.matches(rawPassword, user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        return user;

    }
    @Override
    public User register(RegisterRequest registerRequest) {
        String username = registerRequest.getUsername();
        String rawPassword = registerRequest.getPassword();

        // 检查用户名是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User existingUser = getOne(queryWrapper);
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建新用户
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(passwordEncoder.encode(rawPassword)); // 加密密码
        newUser.setPoints(0); // 默认积分

        // 保存用户
        save(newUser);

        // 返回用户信息（可选：返回时不包含密码）
        newUser.setPassword(null);
        return newUser;
    }
}



